/**
 * 通用弹窗
 * @param {string} title 弹窗标题
 * @param {string} content 弹窗内容
 * @param {string} cancelText 取消按钮文案
 * @param {string} confirmText 确定按钮文案
 * @param {BOOL} showCancel 是否展示取消按钮
 * @returns {Promise}
 */
export const alert = (param) => {
  param = { title: '', content: '', cancelText: '取消', confirmText: '确认', showCancel: true, ...param }
  return new Promise((resolve, reject) => {
    uni.showModal({
      ...param,
      cancelColor: '#666666',
      confirmColor: '#246DF1',
      success: res => {
        if (res.confirm) {
          resolve()
        } else if (res.cancel || (!res.cancel && !res.confirm)) {
          reject(new Error(0))
        }
      },
      fail: () => {
        reject(new Error(0))
      }
    })
  })
}

/*
* 时间差计算 毫秒
* startDate==>开始时间
* endDate==>结束时间
*  https://www.jianshu.com/p/bdda96a1dcd8
* */
export function diffTime (startDate, endDate) {
  const diff = endDate - startDate// .getTime();//时间差的毫秒数
  // 计算出相差天数
  return Math.floor(diff / (24 * 3600 * 1000))
}

/* 扫码进入book页
* 获取bookId
*
 **/
export function urlQuery (name, url) {
  if (!url) url = location.href
  name = name.replace(/[[]/, '\\[').replace(/[\]]/, '\\]')
  const regexS = '[\\?&]' + name + '=([^&#]*)'
  const regex = new RegExp(regexS)
  const results = regex.exec(url)
  return results == null ? null : results[1]
}

export function processImage (src) {
  if (src) {
    if (src && ~src.indexOf('.gif')) return src
    if (uni.flux.store.state.env.isAndroid || uni.flux.store.state.systemInfo.iosSystemVersion >= 14) {
      return src + '?x-oss-process=image/format,jpg/quality,q_80/format,webp'
    } else {
      return src + '?x-oss-process=image/format,jpg/quality,q_80/format,jpg'
    }
  }
  return ''
}

export function processImage2 (src, interlace, Qnum) {
  const type = 'q' // Q 绝对质量 q相对质量
  // 模糊过渡处理
  interlace = interlace ? `interlace,${interlace}` : 'interlace,1'
  Qnum = Qnum || 92
  if (!src) return ''
  if (src) {
    if (src && ~src.indexOf('.gif')) return src
    if (uni.flux.store.state.env.isAndroid || uni.flux.store.state.systemInfo.iosSystemVersion >= 14) {
      return `${src}?x-oss-process=image/format,webp/quality,${type}_${Qnum}/${interlace}`
    } else {
      return `${src}?x-oss-process=image/format,jpg/quality,${type}_${Qnum}/${interlace}`
    }
  }
}

export function navigateTo (url) {
  uni.navigateTo({ url })
}

/**
 * 根据linkType跳转
 * from 页面来源
 */
export function linkTypeNavigateTo (item, from, entrance) {
  const id = item.link || item.cardId || item.id
  uni.flux.track.BannerClick({
    property: {
      banner_title: item.title,
      banner_position: item.positionName,
      banner_type: item.linkTypeName,
      banner_grade: from !== 'lesson' ? uni.flux.store.state.bookInfo.gradeName : '',
      banner_content: item.linkType === 'UNION_CARD' ? item.linkTypeName : (item.linkType === 'INTENTION_ACTIVITY' ? item.linkTypeName : '')
    }
  })
  if (item.linkType === 'UNION_CARD') {
    return navigateTo(`/pages/book/sub/buy-lesson/index?cardId=${id}&bookId=${uni.flux.store.state.bookId}&from=${from}&entrance=${entrance}`)
  }
  if (item.linkType === 'VIDEO_CLASS') {
    return navigateTo(`/pages/book/sub/video-lesson/index?albumId=${id}&bookId=${uni.flux.store.state.bookId}`)
  }
  if (item.linkType === 'INTENTION_ACTIVITY') {
    return navigateTo(`/pages/other/activity/index?id=${id}`)
  }
  if (item.linkType === 'WEBPAGE') {
    if (uni.flux.store.state.env.isWeixin) {
      return navigateTo(`/pages/other/webview/index?viewUrl=${encodeURIComponent(id)}`)
    }
    window.location.href = id
  }
  if (item.linkType === 'APPLETS') {
    return uni.navigateToMiniProgram({
      appId: item.appId,
      path: id,
      extraData: {
        data1: 'test'
      },
      success (res) {
        // console.log('success打开小程序')
      }
    })
  }
  console.error('linkTypeNavigateTo, id:' + id + ' linkType:' + item.linkType)
}

export function navigateBack () {
  const pages = getCurrentPages()
  if (pages.length === 1) {
    uni.switchTab({
      url: '/pages/index/index'
    })
  } else {
    uni.navigateBack()
  }
}

export function getRandom (m) {
  let num = ''
  for (let i = 0; i < m; i++) {
    const val = parseInt(Math.random() * 10, 10)
    if (i === 0 && val === 0) {
      i--
      continue
    }
    num += val
  }
  return num
}

/**
 * 获取 url 参数
 * @param name
 * @returns {string|string|*}
 */
export function getQuery (name) {
  const reg = new RegExp('(\\?|&)' + name + '=([^&]*)(&|$)', 'i')
  const m = window.location.search.match(reg)
  return m && m.length > 2 ? decodeURIComponent(m[2]) : ''
}

export const params2json = function (params = '', slice = '&') {
  const result = {}
  params.split(slice).forEach((item) => {
    const arr = item.split('=')
    const key = arr[0] || ''; const value = arr[1] || ''
    if (item && key) {
      result[key] = value
    }
  })
  return result
}

export const json2params = function (json = {}, slice = '&') {
  return Object.keys(json).reduce((acc, item) => {
    return acc + '' + item + '=' + json[item] + slice
  }, '').slice(0, -1)
}

export function getCurrentPageFullPath () {
  const pages = getCurrentPages()
  const router = pages.length > 1 ? pages[pages.length - 1] : pages[0]

  const curPath = {
    route: '/pages/index/index',
    fullPath: '/pages/index/index'
  }
  if (router) {
    if (router.route && !router.route.startsWith('/pages/')) {
      curPath.route = '/' + router.route
    }
    curPath.fullPath = router.$page.fullPath
  } else {
    if (uni.flux.store.state.env.isH5) {
      curPath.route = window.location.pathname
      curPath.fullPath = window.location.pathname + window.location.search
    }
  }
  // console.log('getCurrentPages：', curPath)
  return curPath
}

export function notWifiNetworkTip () {
  if (['2g', '3g', '4g', '5g'].includes(uni.flux.store.state.systemInfo.networkType)) {
    uni.showToast({ icon: 'none', title: '当前网络非wifi', duration: 3000 })
  }
}

/**
 * 微信开放标签
 * 微信版本要求为：7.0.12及以上。 系统版本要求为：iOS 10.3及以上、Android 5.0及以上
 */
export function checkWechatAppVersion () {
  // #ifdef H5
  // 获取微信的版本号，如： 7.0.14  8.0.1
  const wechat = navigator.userAgent.match(/MicroMessenger\/([\d.]+)/i)
  if (wechat) {
    const judgewechat = wechat[1].split('.')

    // 大于7的版本
    if (judgewechat[0] > 7) {
      this.canJump = true
      return true
    }

    if (judgewechat[0] >= 7) {
      // 7.1
      if (judgewechat[1] > 0) {
        this.canJump = true
        return true
      }

      if (judgewechat[1] >= 0) {
        if (judgewechat[2] >= 12) {
          // 微信版本是 7.0.12及以上
          return true
        }
      }
    }
    return false
  }
  return false
  // #endif
}
